<template>
  <el-dialog :title="title" :visible="visible" width="630px" @close="closeFn" :modal="false">
    <el-form
      :model="nodeForm"
      :rules="rules"
      ref="nodeForm"
      v-if="type !== 'preview'"
    >
      <el-form-item label="点位名称：" :label-width="'140px'" prop="name">
        <el-input
          autocomplete="off"
          placeholder="请输入"
          maxlength="15"
          show-word-limit
          v-model="nodeForm.name"
          :validate-event="false"
        ></el-input>
      </el-form-item>
      <el-form-item label="所在区域：" :label-width="'140px'" prop="regionId">
        <el-select
          placeholder="请选择"
          style="width: 396px"
          v-model="nodeForm.regionId"
          :validate-event="false"
        >
          <el-option
            v-for="item in regionList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在商圈：" :label-width="'140px'" prop="businessId">
        <el-select
          placeholder="请选择"
          style="width: 396px"
          v-model="nodeForm.businessId"
          :validate-event="false"
        >
          <el-option
            v-for="item in businessList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="归属合作商：" :label-width="'140px'" prop="ownerId">
        <el-select
          placeholder="请选择"
          style="width: 396px"
          v-model="nodeForm.ownerId"
          @change="ownerSelect"
        >
          <el-option
            v-for="item in partnerList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址：" :label-width="'140px'" prop="areaCode">
        <el-cascader
          :options="regionData"
          v-model="nodeForm.areaCode"
          placeholder="请选择"
          @change="araeSelect"
          :validate-event="false"
          clearable
          ref="cascader"
        ></el-cascader>
      </el-form-item>
      <el-form-item :label-width="'140px'" prop="addr">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入详细地址"
          maxlength="60"
          show-word-limit
          v-model="nodeForm.addr"
          :validate-event="false"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <template v-if="type === 'preview'">

          <el-table
            v-loading="loading"
            :data="vmList"
            empty-text
            :cell-style="{ padding: '2px 0', border: 'none' }"
            :header-cell-style="{ background: '#f4f6fa' }"
          >
            <el-table-column label="序号" type="index" :index="1" width="80">
            </el-table-column>
            <el-table-column label="机器编号" width="157" prop="innerCode">
            </el-table-column>
            <el-table-column label="设备状态" width="157" prop="vmStatus" :formatter="formatStatus">
            </el-table-column>
            <el-table-column label="最后一次供货时间" width="158" :formatter="formatTime" prop="lastSupplyTime">
            </el-table-column>
          </el-table>

    </template>
    <div slot="footer" class="dialog-footer" v-if="type !== 'preview'">
      <el-button @click="closeFn" class="cancel">取消</el-button>
      <el-button type="primary" @click="submit">确认</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 引入省市区联动数据
import { regionData, CodeToText } from 'element-china-area-data'
import { businessType, partner, addNode, updateNode } from '@/api/dianwei'
// console.log(CodeToText)
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    type: {
      type: String,
      required: true
    },
    regionList: {
      type: Array,
      required: true
    },
    nodeList: {
      type: Array,
      required: true
    },
    loading: {
      type: Boolean,
      default: false
    },
    vmList: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      nodeForm: {
        addr: '',
        areaCode: '',
        businessId: '',
        createUserId: this.$store.state.user.userId,
        name: '',
        ownerId: '',
        ownerName: '',
        regionId: ''
      },
      businessList: [],
      partnerList: [],
      regionData: regionData,
      rules: {
        name: [
          { required: true, message: '请输入名称' },
          {
            validator: (rules, value, callback) => {
              let isRepeat = false
              if (this.nodeForm.id) {
                isRepeat = this.nodeList.filter(item => item.id !== this.nodeForm.id).some(item => item.name === value)
              } else {
                isRepeat = this.nodeList.some(item => item.name === value)
              }
              isRepeat ? callback(new Promise(this.$message.error('已有相同的点位名'))) : callback()
            }
          }
        ],
        regionId: [
          { required: true, message: '请选择所在区域' }
        ],
        businessId: [
          { required: true, message: '请选择商圈' }
        ],
        ownerId: [
          { required: true, message: '请选择合作商' }
        ],
        areaCode: [
          { required: true, message: '请选择地区' }
        ],
        addr: [
          { required: true, message: '请输入详细地址' }
        ]
      },
      areaString: ''
    }
  },
  created () {
    this.getBusiness()
    this.getPartner()
  },
  computed: {
    title () {
      let text = null
      if (this.type === 'preview') {
        text = '点位详情'
      } else if (this.type === 'add') {
        text = '新增点位'
      } else if (this.type === 'edit') {
        text = '修改点位'
      }
      return text
    }
  },
  methods: {
    closeFn () {
      this.nodeForm = {
        addr: '',
        areaCode: '',
        businessId: '',
        createUserId: this.$store.state.user.userId,
        name: '',
        ownerId: '',
        ownerName: '',
        regionId: ''
      }
      if (this.type !== 'preview') {
        this.$refs.nodeForm.resetFields()
        // 清空选中的地区节点
        this.$refs.cascader.$refs.panel.clearCheckedNodes()
      }
      this.$emit('update:visible', false)
    },
    // 商圈列表
    async getBusiness () {
      this.businessList = await businessType()
    },
    // 合作商列表
    async getPartner () {
      const { currentPageRecords } = await partner({ pageIndex: 1, pageSize: 100000 })
      this.partnerList = currentPageRecords
    },
    // 合作商select发生改变时触发
    ownerSelect (id) {
      this.nodeForm.ownerName = this.partnerList.find(item => item.id === id).name
    },
    // 地区选择发生改变时触发
    araeSelect (valueArr) {
      // 将省市区的字符串拼接到addr上 用于传参
      this.areaString = CodeToText[valueArr[0]] + '-' + CodeToText[valueArr[1]] + '-' + CodeToText[valueArr[2]]
    },
    async submit () {
      try {
        await this.$refs.nodeForm.validate()
        if (this.nodeForm.id) {
          await updateNode({ ...this.nodeForm, areaCode: this.nodeForm.areaCode.slice(-1).toString(), addr: this.areaString + '-' + this.nodeForm.addr })
          this.$message.success('修改成功')
        } else {
          await addNode({ ...this.nodeForm, areaCode: this.nodeForm.areaCode.slice(-1).toString(), addr: this.areaString + '-' + this.nodeForm.addr })
          this.$message.success('新增成功')
        }
        this.$parent.getNodeList()
        this.closeFn()
      } catch (e) {
      }
    },
    formatStatus (row, column, cellValue, index) {
      if (cellValue === 1) return '运营'
      if (cellValue === 0) return '未投放'
      else return '未知'
    },
    formatTime (row, column, cellValue, index) {
      return cellValue.replace(/-/g, '.').replace('T', ' ')
    }
  }
}
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}
::v-deep .el-dialog {
  border-radius: 10px;
}
::v-deep .el-dialog__header {
  padding: 20px;
  padding-bottom: 10px;
  .el-dialog__title {
    line-height: 22px !important;
    font-size: 16px !important;
    font-weight: 600;
  }
}
::v-deep .el-dialog__body {
  padding: 20px 20px 30px;
  color: #666;
  .el-form-item {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
    .el-form-item__content {
      line-height: 36px;
      width: 396px;
      .el-input .el-input__inner {
        height: 36px;
        line-height: 36px;
      }
      .el-textarea__inner {
        height: 82px;
      }
    }
  }
}
::v-deep .el-dialog__footer {
  padding-top: 0;
  padding-bottom: 40px;
  .dialog-footer {
    text-align: center;
    .el-button {
      padding: 0;
      // height: 100%;
      width: 80px;
      background: linear-gradient(135deg, #f28a59, #e85c31);
      border: none;
      line-height: 36px;
      color: white;
      margin-left: 34px;
      font-size: 14px;
      &.cancel {
        background: #fbf4f0 !important;
        color: #655b56 !important;
        margin-left: 0px;
      }
    }
  }
}
.el-cascader {
  width: 396px;
}
.el-table{
  margin:0 20px
}
::v-deep .el-table__header-wrapper {
  .el-table__cell {
    color: #666666;
    height: 42px;
    padding: 0 !important;
    font-weight: 400;
    border-bottom: none !important;
  }
}
::v-deep .el-table__body-wrapper {
  .el-table__cell {
    color: #666666;
    height: 44px;
    padding: 10px 0 !important;
    font-weight: 400;
    // border-bottom:none !important
  }
}
</style>
<style>
.el-cascader-menu {
  height: 180px;
  width: 100px;
}
</style>
